package com.cash.app.ui.loan.adapter

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import coil3.load
import coil3.request.placeholder
import com.cash.app.R
import com.cash.app.databinding.AcLoanConfirmItemBinding
import com.cash.app.ui.loan.model.RecommendDataResponse
import com.cash.app.utils.NumberUtils

class RecommendListAdapter : RecyclerView.Adapter<RecommendListAdapter.ViewHolder>() {

    private var items: List<RecommendDataResponse.Product> = emptyList()
    private val selectedItems = mutableSetOf<Int>()

    @SuppressLint("NotifyDataSetChanged")
    fun setData(data: List<RecommendDataResponse.Product>) {
        items = data
        selectedItems.clear()
        notifyDataSetChanged()
    }

    fun getSelectedProducts(): List<RecommendDataResponse.Product> {
        return items.filterIndexed { index, _ -> selectedItems.contains(index) }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val binding = AcLoanConfirmItemBinding.inflate(
            LayoutInflater.from(parent.context), parent, false
        )
        return ViewHolder(binding)
    }

    override fun getItemCount(): Int = items.size

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        selectedItems.add(position)
        holder.bind(items[position], selectedItems.contains(position))
    }

    inner class ViewHolder(
        private val binding: AcLoanConfirmItemBinding
    ) : RecyclerView.ViewHolder(binding.root) {

        init {
            binding.cbSelect.setOnCheckedChangeListener { _, isChecked ->
                val position = adapterPosition
                if (position != RecyclerView.NO_POSITION) {
                    if (isChecked) {
                        selectedItems.add(position)
                    } else {
                        selectedItems.remove(position)
                    }
                }
            }
        }

        fun bind(product: RecommendDataResponse.Product, isSelected: Boolean) {
            with(binding) {
                if (product.p_icon.isNotEmpty()) {
                    productIcon.load(product.p_icon) {
                        placeholder(R.mipmap.app_icon)
                    }
                }
                tvProductName.text = product.p_name
                tvAmount.text = NumberUtils.toRupeeWithComma(product.p_money)
                tvTenure.text = binding.root.context.getString(
                    R.string.unit_tenure, product.p_peroid.toString()
                )
                tvRate.text = binding.root.context.getString(R.string.unit_rate, product.p_rate)
                cbSelect.isChecked = isSelected
            }
        }
    }
} 